#pragma once
#include "cgzITask.h"

struct MYSQL;
struct MYSQL_RES;

enum class cgzMysqlCode
{
    NONE,         // 无响应
    AUTH_SUCCESS, // 认证成功
    EXEC_REQUEST, // 执行请求
    EXEC_REPLY,   // 执行回复
};

enum class cgzCMysqlCmd
{
    INSERT,
    UPDATE,
    DELETE,
    SELECT,
    CREATE,
    DROP,
    ALTER,
    TRUNCATE,
    EXPLAIN,
    SHOW,
    SET,
    USE,
};

class cgzCMysqlReply : public cgzIData
{
public:
    cgzCMysqlReply(cgzMysqlCode code);
    virtual ~cgzCMysqlReply();

public:
    cgzMysqlCode m_code;
};

class cgzCMysqlExec : public cgzCMysqlReply
{
public:
    cgzCMysqlExec(const cgzCMysqlCmd cmd, const char *sql, const int cookid = -1);
    virtual ~cgzCMysqlExec();

public:
    // 请求参数
    cgzCMysqlCmd m_cmd;
    std::string m_sql;
    std::vector<std::string> m_blobs; // 二进制数据
    // 回复参数
    long m_cookid;
    bool m_ret;
    bool m_err;
    long m_sort;
    MYSQL_RES *m_reply;
};

class cgzCMysql : public cgzITask
{
public:
    cgzCMysql(
        cgzCThreadPool *pool,
        const char *name,
        const char *ip,
        const char *use,
        const char *password,
        const int port,
        const char *db,
        const char *charset,
        const int cid);
    virtual ~cgzCMysql();

public:
    bool run(int64_t nms) override;
    bool addTask(cgzIData *) override;

public:
    bool connect();
    bool rconnect();
    void authret();

protected:
    std::string m_ip;
    std::string m_user;
    std::string m_password;
    std::string m_db;
    std::string m_charset;
    bool m_firstAuth;
    int m_port;
    int m_cid;
    int m_fd;

private:
    MYSQL *m_mysql;
};
